#include <stdlib.h>
#include <stdio.h>
#include "proto.h"
#include "server.h"
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include "mlib.h"
#include "list.h"
#include "channel.h"
#include <pthread.h>

struct msg_list_st *list_entry;
int num_list_entry;
pthread_t list_tid;
struct msg_list_st *entrylistptr;  //节目单总包
struct msg_listentry_st *entryptr; //每一个节目的包

void *thr_list(void *thr)
{
    // printf("%d\n", __LINE__);
    int ret;

    struct msg_listentry_st *ptr;
#ifdef DEBUG
    int i = 0;
    for (ptr = list_entry->entry; i < num_list_entry; ptr = (void *)((char *)ptr) + ntohs(ptr->len))
    {
        i++;
        printf("channel:%d:%s", ptr->chnid, ptr->desc);
    }
#endif // DEBUG

    while (1)
    {
        syslog(LOG_INFO, "thr_list sndaddr :%d\n", sndaddr.sin_addr.s_addr);
        ret = sendto(sfd, list_entry, totalsize, 0, (void *)&sndaddr,
                     sizeof(sndaddr)); // 频道列表在广播网段每秒发送entrylist
        syslog(LOG_DEBUG, "List sent content len:%d\n", totalsize);
        if (ret < 0)
        {
            syslog(LOG_WARNING, "sendto(serversd, enlistp...:%s", strerror(errno));
        }
        else
        {
            syslog(LOG_DEBUG, "List sendto(serversd, enlistp....):success");
        }
        sleep(1);
    }
}

int thr_list_create(struct msg_list_st *listptr, int num_ent)
{
    int err;
    list_entry = listptr;     //接收节目单的包 所有的节目单包的首地址
    num_list_entry = num_ent; //频道的个数
    err = pthread_create(&list_tid, NULL, thr_list, NULL);
    if (err)
    {
        syslog(LOG_ERR, "pthread_create():%s\n", strerror(errno));
        return -1;
    }

    return 0;
}
// 销毁节目单线程
int thr_list_destroy(void)
{
    pthread_cancel(list_tid);
    pthread_join(list_tid, NULL);
    free(entrylistptr);
    return 0;
}